package com.ice.app.system.organ.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.github.pagehelper.util.StringUtil;
import com.ice.app.system.entity.Organ;
import com.ice.app.system.mapper.OrganMapper;
import com.ice.app.system.organ.vo.OrganTreeVo;
import com.ice.app.system.organ.vo.OrganUserRelVo;
import com.iceframework.core.utils.KeyUtils;
import com.iceframework.core.utils.TreeParserUtils;

/**
 * 
 * 业务逻辑层： 组织机构管理
 * 
 * @author Mr.Palo
 * @email 442803840@qq.com
 * 
 */
@Service
public class OrganService {

	@Autowired
	private OrganMapper organMapper;

	// ----------------------------------------自动生成--------------------------------------------

	/**
	 * 菜单保存
	 * 
	 * @param organ
	 * @return
	 * @throws Exception
	 */
	@Transactional
	public boolean saveOrgan(Organ organ) throws Exception {
		if (StringUtil.isNotEmpty(organ.getOrganId())) {
			// 修改操作
			Organ old = this.getOrgan(organ.getOrganId());
			organ.setUpdateBy("admin");
			organ.setUpdateDate(new Date());
			if (old != null) {
				return organMapper.updateByPrimaryKeySelective(organ) > 0;
			}
			return false;
		} else {
			// 保存操作
			String key = KeyUtils.genKey("Organ");
			organ.setOrganId(key);
			organ.setCreateBy("admin");
			organ.setCreateDate(new Date());
			organ.setUpdateBy("admin");
			organ.setUpdateDate(new Date());
			
			if(!organ.getParentId().equals("0")){
				Organ parent = new Organ();
				parent.setCode(organ.getParentId());
				Map<String,Object> map = new HashMap<String,Object>();
				map.put("organ", parent);
				List<Organ> selectByFilter = organMapper.selectByFilter(map);
				organ.setSyscode(selectByFilter.get(0).getSyscode()+organ.getCode()+"@");
			}else{
				organ.setSyscode(organ.getCode()+"@");
			}
			
			return organMapper.insertSelective(organ) > 0;
		}
	}

	/**
	 * 根据主键删除菜单
	 * 
	 * @param key
	 * @return
	 */
	@Transactional
	public boolean deleteOrgan(String key) {
		return organMapper.deleteByPrimaryKey(key) > 0;
	}

	/**
	 * 根据多个主键删除菜单
	 * 
	 * @param keys
	 * @return
	 */
	@Transactional
	public boolean deleteOrgans(String keys) {
		if (!StringUtils.isEmpty(keys)) {
			String[] strs = keys.split(",");
			for (String key : strs) {
				this.deleteOrgan(key);
			}
			return true;
		}
		return false;
	}

	/**
	 * 根据主键获取菜单实体
	 * 
	 * @param key
	 * @return
	 */
	public Organ getOrgan(String key) {
		return organMapper.selectByPrimaryKey(key);
	}

	/**
	 * 根据给定条件获取菜单实体集合
	 * 
	 * @param key
	 * @return
	 */
	public List<Organ> getOrgans(Organ organ) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("organ", organ);
		return organMapper.selectByFilter(map);
	}
	
	/**
	 * 取机构下拉树
	 * 
	 * @param key
	 * @return
	 */
	public List<OrganTreeVo> getOrganTreeSelect(String userId,String organCode) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("organ", new Organ());
		List<Organ> organs = organMapper.selectByFilter(map);
		List<OrganTreeVo> trees = TreeParserUtils.getTreeList(organCode, transOrganTreeVo(organs));
		return trees;
	}

	// ----------------------------------------自定义（Public）---------------------------------------------


	/**
	 * 转换TreeVo
	 * 
	 * @param menus
	 * @return
	 */
	private List<OrganTreeVo> transOrganTreeVo(List<Organ> organs) {
		if (organs != null && organs.size() != 0) {
			List<OrganTreeVo> trees = new ArrayList<>();
			for (Organ organ : organs) {
				OrganTreeVo temp = new OrganTreeVo();
				temp.setId(organ.getOrganId());
				temp.setParentId(organ.getParentId());
				temp.setName(organ.getName());
				temp.setOpen("true");
				temp.setOrganCode(organ.getCode());
				trees.add(temp);
			}
			return trees;
		}
		return null;
	}

	/**
	 *	获取机构树
	 * @param userId
	 * @return
	 */
	public List<OrganTreeVo> getOrganTreeByUserId(String userId){
		List<OrganTreeVo> organ = organMapper.selectOrganTreeByUserId(userId);
		OrganTreeVo organTreeVo = new OrganTreeVo();
		organTreeVo.setName("组织机构");
		organTreeVo.setId("root");
		organTreeVo.setChecked(false);
		organ.add(organTreeVo);
		return organ;
	}
	
	/**
	 *	获取机构树
	 * @param userId
	 * @return
	 */
	public List<OrganTreeVo> getOrganTreeInfoByUserId(String userId){
		List<OrganTreeVo> organ = organMapper.selectInfoOrganTreeByUserId(userId);
		return organ;
	}
	
	/**
	 * 保存用户和机构之间的关系
	 * @param userId
	 * @param organIds
	 * @return
	 */
	@Transactional
	public boolean saveOrganUserRel(String userId, String organIds) {
		// TODO Auto-generated method stub
		organMapper.deleteOrganUserRelByUserId(userId);
		String[] split = organIds.split(",");
		List<OrganUserRelVo> rels = new ArrayList<OrganUserRelVo>();
		for (String organId : split) {
			if(organId.equals("root")){
				continue;
			}else if(!organId.equals("")){
				OrganUserRelVo temp = new OrganUserRelVo();
				temp.setId(KeyUtils.genUUID());
				temp.setOrganId(organId);
				temp.setUserId(userId);
				rels.add(temp);
			}
		}
		boolean result = true;
		for (OrganUserRelVo record : rels) {
			result = result&organMapper.insertOrganUserRelByUserId(record)>0;
		}
		return result;
	}
}